//
//  KDHttpRequest.m
//  KDTools
//
//  Created by 斌 on 15/11/19.
//  Copyright © 2015年 斌. All rights reserved.
//

#import "KDHttpRequest.h"
#define kTimeoutInterval 60.0f //默认60秒

@implementation KDHttpRequest



+ (void)sendRequestWithURLString:(NSString *)urlString
                      httpMethod:(NSString *)HTTPMethod
                    successBlock:(void (^)(NSString *retData))successBlock
                     failedBlock:(void (^)(NSString *errMsg))failedBlock{
    
    [self sendRequestWithURLString:urlString andDataDict:nil timeoutInterval:kTimeoutInterval httpMethod:HTTPMethod successBlock:successBlock failedBlock:failedBlock];
    
}


+ (void)sendRequestWithURLString:(NSString *)urlString
                     andDataDict:(NSDictionary *)dict
                 timeoutInterval:(NSTimeInterval)timeoutInterval
                      httpMethod:(NSString *)HTTPMethod
                    successBlock:(void (^)(NSString *retData))successBlock
                     failedBlock:(void (^)(NSString *errMsg))failedBlock{
    
   
    
    dispatch_queue_t queue = dispatch_queue_create("KDHttpRequest", NULL);
    dispatch_async(queue, ^{
        
        NSString *newUrl = urlString;
        NSString *tmpTxt = @"";
        printf("\n|-----------------------------------------------");
        for ( NSString *tmpKey in dict.allKeys ) {
            
            NSString *value = [NSString stringWithFormat:@"%@",[dict objectForKey:tmpKey]];
            tmpTxt = [tmpTxt stringByAppendingFormat:@"%@=%@&",tmpKey,[dict objectForKey:tmpKey]];
            printf("\n| %s = %s ",[tmpKey UTF8String],[value UTF8String]);
        }
        printf("\n|-----------------------------------------------");
        printf("\n| url = %s",[newUrl UTF8String]);
        printf("\n| method = %s",[HTTPMethod UTF8String]);
        printf("\n| url + body = %s?%s",[newUrl UTF8String],[tmpTxt UTF8String]);
        printf("\n|-----------------------------------------------");
        
        if ([HTTPMethod isEqualToString:@"GET"]){
            
            newUrl = [newUrl stringByAppendingFormat:@"?%@",tmpTxt];
        }
        
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
        [request setURL:[NSURL URLWithString:[newUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]]];
        [request setTimeoutInterval:timeoutInterval];
        [request setHTTPMethod:HTTPMethod];
        if ([HTTPMethod isEqualToString:@"POST"]){
            NSData *postData = [tmpTxt dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
            NSString *postLength = [NSString stringWithFormat:@"%d", (int)[postData length]];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            [request setHTTPBody:postData];
        }
       
        
        NSError *err;
        NSData *returnData = [NSURLConnection sendSynchronousRequest:request
                                                   returningResponse:nil
                                                               error:&err];
        
        dispatch_sync(dispatch_get_main_queue(), ^{
            if ([NSThread isMainThread]) {
                
                if (!err) {
                    
                    NSString *result = [[NSString alloc] initWithData:returnData  encoding:NSUTF8StringEncoding];
                    printf("\n| retData = %s\n",[result UTF8String]);
                    successBlock(result);
                    
                }else{
                    
                    NSString *errMsg = [err localizedDescription];
                    printf("\n| errMsg = %s\n",[errMsg UTF8String]);
                    failedBlock(errMsg);
                }

            }
        });
        
    });

}



@end
